package com.cxs.basic;

import com.cxs.util.MqttUtil;
import org.eclipse.paho.client.mqttv3.*;
import org.junit.Test;

import java.io.IOException;

/**
 * @Author CXS
 * @Date 2024/1/26 14:19
 **/
public class PubSubTest {

    String subTopic = "testtopic/#";

//    String pubTopic = "testtopic/1";
    String pubTopic = "testtopic/aa";

    @Test
    public void pub() throws IOException {
        String content = "Hello World";
        int qos = 2;
        String clientId = "cxs-java-testa";
        MqttClient client = MqttUtil.createMqttClient(clientId, true);

        // 消息发布所需参数
        MqttMessage message = new MqttMessage(content.getBytes());
        message.setQos(qos);
        try {
            client.publish(pubTopic, message);
            System.out.println("Message published");

            client.disconnect();
            client.close();

            System.in.read();
        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }


    @Test
    public void sub() throws IOException {
        String clientId = "cxs-java-test";
        MqttClient client = MqttUtil.createMqttClient(clientId, true);

        client.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable throwable) {
                System.out.println("connectionLost");
                System.out.println("throwable" + throwable.getMessage());
                try {
                    client.reconnect();
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                System.out.println("收到了消息" + s);
                System.out.println("消息信息为" + mqttMessage.toString());
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                System.out.println("deliveryComplete完成" + iMqttDeliveryToken.toString());
            }
        });
        try {
            client.subscribe(subTopic);

            System.in.read();

        } catch (MqttException e) {
            e.printStackTrace();
        }

    }

}

